package com.tianji.learning.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tianji.api.client.course.CourseClient;
import com.tianji.api.dto.course.CourseFullInfoDTO;
import com.tianji.api.dto.leanring.LearningLessonDTO;
import com.tianji.api.dto.leanring.LearningRecordDTO;
import com.tianji.common.exceptions.BadRequestException;
import com.tianji.common.utils.BeanUtils;
import com.tianji.common.utils.UserContext;
import com.tianji.learning.domain.dto.LearningRecordFormDTO;
import com.tianji.learning.domain.po.LearningLesson;
import com.tianji.learning.domain.po.LearningRecord;
import com.tianji.learning.enums.LessonStatus;
import com.tianji.learning.enums.SectionType;
import com.tianji.learning.mapper.LearningRecordMapper;
import com.tianji.learning.service.ILearningLessonService;
import com.tianji.learning.service.ILearningRecordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 学习记录表 服务实现类
 * </p>
 *
 * @author lyh
 * @since 2024-12-06
 */
@Service
public class LearningRecordServiceImpl extends ServiceImpl<LearningRecordMapper, LearningRecord> implements ILearningRecordService {
    @Autowired
    private ILearningLessonService learningLessonService;
    @Autowired
    private CourseClient courseClient;
    @Override
    public LearningLessonDTO queryLearningRecordByCourse(Long courseId) {
        Long userId = UserContext.getUser();
        //查询该用户课程号对应的学习课程
        LearningLesson lesson = learningLessonService.lambdaQuery().eq(LearningLesson::getCourseId, courseId).eq(LearningLesson::getUserId, userId).one();
        if(lesson==null){
            return null;
        }
        //获取学习记录
        List<LearningRecord> list = this.lambdaQuery().eq(LearningRecord::getLessonId, lesson.getId()).eq(LearningRecord::getUserId, userId).list();
        List<LearningRecordDTO> learningRecordDTOS = BeanUtils.copyList(list, LearningRecordDTO.class);

        //封装返回结果
        LearningLessonDTO dto = new LearningLessonDTO();
        dto.setId(lesson.getId());
        dto.setLatestSectionId(lesson.getLatestSectionId());
        dto.setRecords(learningRecordDTOS);
        return dto;
    }

    @Override
    public void addLearningRecord(LearningRecordFormDTO formDTO) {
        Boolean isFrist=false;
        //判断是考试还是视频
        if(formDTO.getSectionType()== SectionType.EXAM){
            //考试
          isFrist=handExam(formDTO);
        }else{
            //视频
            isFrist=handVando(formDTO);
        }
     //处理课程逻辑
     handLesson(isFrist,formDTO);
    }

    private void handLesson(Boolean isFrist, LearningRecordFormDTO formDTO) {
        LearningLesson lesson = learningLessonService.getById(formDTO.getLessonId());
        if(lesson==null){
          throw new BadRequestException("课表不存在");
        }
        boolean allFinal=false;
        //第一次学完，潘墩是否全部学完
        if(isFrist){
            CourseFullInfoDTO course = courseClient.getCourseInfoById(lesson.getCourseId(), false, false);
            //判断课程是否存在
            if(course==null){
                throw new BadRequestException("课程不存在");
            }
            //判断是否全部学完
            allFinal = course.getSectionNum() <= lesson.getLearnedSections() + 1;
        }
        learningLessonService.lambdaUpdate()
                .set(lesson.getStatus()==LessonStatus.NOT_BEGIN,LearningLesson::getStatus,LessonStatus.LEARNING)
                //全部修改的字段
                .set(LearningLesson::getLatestLearnTime,formDTO.getCommitTime())
                .set(LearningLesson::getLatestSectionId,formDTO.getSectionId())
                //第一次看完的字段
                .setSql(isFrist,"learned_sections = learned_sections + 1")
                //全学完修改的字段
                .set(allFinal,LearningLesson::getStatus, LessonStatus.FINISHED)
                //修改条件
                .eq(LearningLesson::getId,lesson.getId())
                .update();
    }

    /**
     * 处理视频逻辑
     * @param formDTO
     * @return
     */
    private Boolean handVando(LearningRecordFormDTO formDTO) {
         //判断视频是否看过
        LearningRecord old = this.lambdaQuery().eq(LearningRecord::getLessonId, formDTO.getLessonId()).eq(LearningRecord::getSectionId, formDTO.getSectionId()).one();
        if(old==null){
            //第一次看  默认第一次看不完
            LearningRecord learningRecord = BeanUtils.copyBean(formDTO, LearningRecord.class);
            //填充属性
            learningRecord.setUserId(UserContext.getUser());
            learningRecord.setFinished(false);
            this.save(learningRecord);
            return false;
        }
        //判断是否是第一次完成   视频进度>50% 且完成状态为false
        boolean isFrist = formDTO.getMoment() * 2 > formDTO.getDuration()&&!old.getFinished();
        this.lambdaUpdate()
                //都修改moment字段
                .set(LearningRecord::getMoment,formDTO.getMoment())
                //第一次完成，修改finished和finishtime字段
                .set(isFrist,LearningRecord::getFinished,true)
                .set(isFrist,LearningRecord::getFinishTime,formDTO.getCommitTime())
                //修改条件
                .eq(LearningRecord::getId,old.getId())
                .update();
          return isFrist;
    }

    /**
     * 处理考试逻辑
     * @param formDTO
     * @return
     */
    private Boolean handExam(LearningRecordFormDTO formDTO) {
        //新增学习记录   考试只能进行一次 且一次完成
        LearningRecord learningRecord = BeanUtils.copyBean(formDTO, LearningRecord.class);
        //填充属性
        learningRecord.setUserId(UserContext.getUser());
        learningRecord.setFinished(true);
        learningRecord.setFinishTime(formDTO.getCommitTime());
        this.save(learningRecord);
        return true;
    }
}
